<template>

</template>
<script>
  import Cookie from 'js-cookie'
  import ajax from '../../module/ajax/public'

  export default {
    name: 'Auth',
    created () {
      // 判断openid是否存在，存在，提交登入，否则微信授权
      const userInfo = Cookie.get('userInfo')
      const user = JSON.parse(userInfo || '{}')

      if (user.openid) {
        ajax.doAction({
          url: '/wechatLogin',
          type: 'POST',
          items: {
            openid: user.openid
          },
          successMsg: {
            isshow: false,
            msg: ''
          },
          successCallback: (data) => {
            // console.log(data)
            if (data.code === 200) {
              Cookie.set('token', data.data.access_token, {expires: this.GLOBAL.CookieExpired})
              Cookie.set('userInfo', JSON.stringify(data.data.user), { expires: this.GLOBAL.CookieExpired })
              let backRedirectUrl = Cookie.get('backRedirectUrl') || '/index'
              Cookie.remove('backRedirectUrl')
              window.location.href = backRedirectUrl
            } else {
              window.location.href = '/login'
            }
          },
          errorCallback: (data) => {
            console.log('请求失败')
          }
        })
      } else {
        let code = this.$route.query.code
        if (!code) {
          window.location.href = process.env.API_ROOT + '/wechat/getCode'
        } else {
          ajax.doAction({
            url: '/wechat/user',
            type: 'POST',
            items: {
              code: code
            },
            successMsg: {
              isshow: false,
              msg: ''
            },
            successCallback: (data) => {
              Cookie.set('userInfo', JSON.stringify(data.data), {expires: this.GLOBAL.CookieExpired})
              let backRedirectUrl = Cookie.get('backRedirectUrl') || '/index'
              Cookie.remove('backRedirectUrl')
              window.location.href = backRedirectUrl
            },
            errorCallback: (data) => {
              console.log('请求失败')
            }
          })
        }
      }
    },
    data () {
      return {}
    },
    methods: {}
  }
</script>
<style>

</style>
